document.addEventListener('DOMContentLoaded', function() {
    // 更新购物车数量
    updateCartCount();
    
    // 设置登录状态
    updateLoginStatus();
    
    // 从URL获取商品ID
    const urlParams = new URLSearchParams(window.location.search);
    const productId = parseInt(urlParams.get('id'));
    
    // 加载商品详情
    if (productId) {
        loadProductDetails(productId);
    } else {
        // 如果没有商品ID，重定向到首页
        window.location.href = 'index.html';
    }
    
    // 添加购物车按钮事件
    document.getElementById('add-to-cart').addEventListener('click', function() {
        const quantity = parseInt(document.getElementById('quantity').value) || 1;
        addToCart(productId, quantity);
    });
    
    // 立即购买按钮事件
    document.getElementById('buy-now').addEventListener('click', function() {
        const quantity = parseInt(document.getElementById('quantity').value) || 1;
        addToCart(productId, quantity);
        window.location.href = 'cart.html';
    });
});

// 加载商品详情
function loadProductDetails(productId) {
    const product = getProductById(productId);
    if (product) {
        document.getElementById('product-name').textContent = product.name;
        document.getElementById('product-price').textContent = `¥${product.price}`;
        document.getElementById('product-description').textContent = product.description || '暂无描述';
        document.getElementById('product-image').src = product.image;
        document.getElementById('product-image').alt = product.name;
        
        // 加载商品规格
        if (product.spec) {
            document.getElementById('product-spec').textContent = product.spec;
        } else {
            document.getElementById('product-spec').parentElement.style.display = 'none';
        }
        
        // 设置最大购买数量
        const stock = product.stock || 99;
        document.getElementById('quantity').max = stock;
        document.getElementById('product-stock').textContent = `库存: ${stock}件`;
    } else {
        // 商品不存在，重定向到首页
        window.location.href = 'index.html';
    }
}

// 添加到购物车
function addToCart(productId, quantity) {
    const product = getProductById(productId);
    if (product) {
        // 获取当前购物车
        let cart = JSON.parse(localStorage.getItem('cart')) || [];
        
        // 检查商品是否已在购物车中
        const existingItemIndex = cart.findIndex(item => item.id === productId);
        
        if (existingItemIndex !== -1) {
            // 商品已在购物车中，增加数量
            cart[existingItemIndex].quantity += quantity;
        } else {
            // 商品不在购物车中，添加新商品
            cart.push({
                id: product.id,
                name: product.name,
                price: product.price,
                image: product.image,
                quantity: quantity
            });
        }
        
        // 保存购物车到本地存储
        localStorage.setItem('cart', JSON.stringify(cart));
        
        // 更新购物车计数
        updateCartCount();
        
        // 显示添加成功提示
        showToast(`${quantity}件 ${product.name} 已添加到购物车`);
    }
}

// 更新购物车数量显示
function updateCartCount() {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const count = cart.reduce((total, item) => total + item.quantity, 0);
    document.getElementById('cart-count').textContent = count;
}

// 更新登录状态
function updateLoginStatus() {
    const loginLink = document.getElementById('login-link');
    const profileLink = document.querySelector('nav ul li a[href="profile.html"]');
    
    if (localStorage.getItem('authToken')) {
        loginLink.textContent = '登出';
        loginLink.href = '#';
        loginLink.addEventListener('click', logout);
        profileLink.style.display = 'block';
    } else {
        loginLink.textContent = '登录';
        loginLink.href = '#';
        loginLink.addEventListener('click', function(e) {
            e.preventDefault();
            localStorage.setItem('redirectAfterLogin', window.location.pathname);
            window.location.href = 'login.html';
        });
        profileLink.style.display = 'none';
    }
}

// 登出功能
function logout() {
    localStorage.removeItem('authToken');
    localStorage.removeItem('userInfo');
    updateLoginStatus();
    showToast('已成功登出');
    setTimeout(() => {
        window.location.reload();
    }, 1000);
}

// 显示提示消息
function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 3000);
}

// 获取商品信息
function getProductById(productId) {
    // 使用你的原始商品数据
    const products = [
        {
            id: 1,
            name: 'Macbook Air',
            price: 9999,
            description: '轻薄便携的笔记本电脑，适合日常办公和娱乐使用。',
            image: 'https://picsum.photos/seed/macbook/300/200',
            category: '电子产品',
            spec: 'M1芯片/8GB/256GB'
        },
        {
            id: 2,
            name: 'iphone16 pro',
            price: 14999,
            description: '最新款旗舰智能手机，拥有超强拍照能力和处理性能。',
            image: 'https://picsum.photos/seed/iphone/300/200',
            category: '电子产品',
            spec: '128GB/深空黑'
        },
        {
            id: 3,
            name: 'iphone16 promax',
            price: 24999,
            description: '大屏旗舰智能手机，适合追求极致体验的用户。',
            image: 'https://picsum.photos/seed/iphonepromax/300/200',
            category: '电子产品',
            spec: '256GB/金色'
        },
        {
            id: 4,
            name: 'ipone15 plus',
            price: 7999,
            description: '性价比高的智能手机，拥有大屏幕和长续航。',
            image: 'https://picsum.photos/seed/iphone15/300/200',
            category: '电子产品',
            spec: '128GB/蓝色'
        }
    ];
    
    return products.find(product => product.id === productId);
}